<template>
  <div>
    <el-tree
      ref="treeRef"
      :data="treeList"
      :props="treeProps"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="checkList"
    ></el-tree>
  </div>
  <div class="button">
    <el-button type="primary" size="large" @click="submitFn">保存</el-button>
    <el-button size="large" @click="resetChecked">清空</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { treeListApi, getRoleMenuByIdApi, allocMenuApi } from "./api";
import { useRoute } from "vue-router";
import { ElMessage, ElTree } from "element-plus";

const route = useRoute();
const treeRef = ref<InstanceType<typeof ElTree>>();
const treeProps = {
  // children属性是要告诉 tree 组件，在data里面哪个属性名是用来作用子级的
  children: "children",
  //   lable 是告诉 tree组件，在data里面哪个属性是用来显示文字的
  label: "title",
};

const checkList = ref<number[]>([]);

const treeList = ref<ItreeMenu[]>([]);

treeListApi().then((res) => {
  if (res.code === 200) {
    treeList.value = res.data;
  }
});

getRoleMenuByIdApi(parseInt(route.query.id as string)).then((res) => {
  if (res.code === 200) {
    checkList.value = res.data.map((item) => item.id) as number[];
  }
});

// 保存
const submitFn = () => {
  // treeRef.value!.getCheckedKeys(true) as number[];
  allocMenuApi({
    roleId: parseInt(route.query.id as string),
    menuIds: treeRef.value!.getCheckedKeys(true) as number[],
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success("保存成功!");
    }
  });
};

// 清空
const resetChecked = () => {
  treeRef.value!.setCheckedKeys([], false);
};
</script>

<style scoped lang="less">
.button {
  margin: 20px;
  display: flex;
  justify-content: center;
}
</style>
